/*
 * @Author: lirl
 * @Date: 2022-07-18 10:45:17
 * @Description: storage util
 */
import { setUserToCookie } from 'jdf-util';
import { isObject } from 'lodash-es';
import settings from '@/settings/settings';
import { ssoLoginPageURL } from './constants';

/**
 * 获取sessionStorage中的值
 * @param name key值
 */
function getSessionStorage(name) {
  return sessionStorage.getItem(name);
}

/**
 * 获取localStorage的值
 * @param name key值
 */
function getLocalStorage(name) {
  return localStorage?.getItem(name);
}

/**
 * 设置localStorage
 * @param name key
 * @param data 值
 */
function setLocalStorage(name, data) {
  localStorage.setItem(name, data);
}

/**
 * 设置sessionStorage
 * @param name key
 * @param data 值
 */
function setSessionStorage(name, data) {
  sessionStorage.setItem(name, data);
}

const { userStorageLocation, tokenStorageLocation } = settings;

/**
 * 获取bff token
 */
export function getBffToken() {
  return tokenStorageLocation === 'LOCAL' ? getLocalStorage(settings.bffTokenKey) : getSessionStorage(settings.bffTokenKey);
}

/**
 * 获取业务端token
 */
export function getToken() {
  return tokenStorageLocation === 'LOCAL' ? getLocalStorage(settings.bizTokenKey) : getSessionStorage(settings.bizTokenKey);
}

/**
 * 从storage中获取信息
 * @param {String} name 存放信息的key
 */
export function getStorageInfo(name) {
  return userStorageLocation === 'LOCAL' ? getLocalStorage(name) : getSessionStorage(name);
}

/**
 * 存储bff端token
 * @param {String} token token信息
 */
export function setBffToken(token) {
  return tokenStorageLocation === 'LOCAL'
    ? setLocalStorage(settings.bffTokenKey, token)
    : setSessionStorage(settings.bffTokenKey, token);
}

/**
 * 设置业务端token
 * @param {String} token token内容
 */
export function setToken(token) {
  tokenStorageLocation === 'LOCAL'
    ? setLocalStorage(settings.bizTokenKey, token)
    : setSessionStorage(settings.bizTokenKey, token);
}

export function setStorageInfo(name, data) {
  userStorageLocation === 'LOCAL' ? setLocalStorage(name, data) : setSessionStorage(name, data);
}

export function removeToken() {
  if (tokenStorageLocation === 'LOCAL') {
    localStorage.removeItem(settings.bizTokenKey);
    localStorage.removeItem(settings.bffTokenKey);
  } else {
    sessionStorage.removeItem(settings.bizTokenKey);
    sessionStorage.removeItem(settings.bffTokenKey);
  }
}

/**
 * 保存用户信息
 * @param {Object} userInfo 用户信息
 */
export function saveUserInfo(userInfo) {
  Object.entries(userInfo).forEach(([k, v]) => setStorageInfo(k, isObject(v) ? JSON.stringify(v) : v));
  setStorageInfo('ssoPage', encodeURIComponent(ssoLoginPageURL));
  // 将数据放入cookie，以便apm获取信息
  setUserToCookie(userInfo);
}

export function clearStorage() {
  if (userStorageLocation === 'LOCAL') {
    localStorage.clear();
  } else {
    sessionStorage.clear();
  }
}

export function setAllToken(token) {
  setBffToken(token);
  setToken(token);
}
